package com.sky.service.impl;

import com.sky.constant.MessageConstant;
import com.sky.entity.DataOrder;
import com.sky.entity.Orders;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.ReportMapper;
import com.sky.service.ReportService;
import com.sky.vo.*;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    ReportMapper reportMapper;

    @Autowired
    WorkspaceServiceImpl workspaceService;

    /**营业额统计*/
    @Override
    @Transactional
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        //数据判空
        if(begin == null || end == null){throw new DeletionNotAllowedException(MessageConstant.UNKNOWN_ERROR);}

        //获取数据并拼装

        //获取在规定时间段中每日的营业额
        List<DataOrder> amounts = reportMapper.QueryAmount(Orders.COMPLETED,LocalDateTime.of(begin,LocalTime.MIN),LocalDateTime.of(end,LocalTime.MAX));

        //获取在规定时间段中有营利的天数
        List<LocalDateTime> orderTime = reportMapper.QueryDate(Orders.COMPLETED,LocalDateTime.of(begin,LocalTime.MIN),LocalDateTime.of(end,LocalTime.MAX));

        end = end.plusDays(1);

        String dateList = begin + ",";
        String turnoverList = "";
        //完成数据的拼接
        while (!begin.isEqual(end)){
        Double amount1 = 0.0;
            for (int i = 0; i < orderTime.size(); i++) {

                while (orderTime.get(i).toLocalDate().isEqual(begin)){//判断该天是否为营利天

                    amount1 += amounts.get(0).getAmount();
                    if(amounts.size() == 1 ){
                        break;}
                    amounts.remove(0);
                }
            }

            if(begin.isEqual(end.plusDays(-2))){

                begin = begin.plusDays(1);
                turnoverList = turnoverList + amount1 + ",";
                dateList += begin;
                continue;
            }
            begin = begin.plusDays(1);
            if (begin.isEqual(end)){
                turnoverList = turnoverList + amount1;
                break;}

            turnoverList = turnoverList + amount1 + ",";
            dateList += begin + ",";
        }

        TurnoverReportVO turnoverReportVO = new TurnoverReportVO();

        turnoverReportVO.setDateList(dateList);
        turnoverReportVO.setTurnoverList(turnoverList);

        return turnoverReportVO;
    }

    /**查询销量排名top10接口*/
    @Override
    @Transactional
    public SalesTop10ReportVO QueryTop(LocalDate begin, LocalDate end) {
        //数据判空
        if(begin == null || end == null){throw new DeletionNotAllowedException(MessageConstant.UNKNOWN_ERROR);}

        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.ofSecondOfDay(00 - 00 - 00));
        LocalDateTime endTime = LocalDateTime.of(end.plusDays(1), LocalTime.ofSecondOfDay(00 - 00 - 00));


        //获取订单id列表
        List<Long> ids = reportMapper.QueryOrderId(beginTime,endTime);

        //根据订单id获取被购的商品名称
        List<String> nameLists = reportMapper.QueryShoppcingName(ids);

        String numberList = "";

        String nameList = "";

        for (int i = 0; i < nameLists.size(); i++) {

            //根据订单和商品名称,查询商品的销量
            Integer number = reportMapper.QueryShoppingSaleCount(ids,nameLists.get(i));

            numberList = ((nameLists.size()-1) != i)?numberList + number + ",":numberList + number;

            nameList = ((nameLists.size()-1) != i)?nameList + nameLists.get(i) + ",":nameList + nameLists.get(i);

        }

        SalesTop10ReportVO salesTop10ReportVO = new SalesTop10ReportVO();

        salesTop10ReportVO.setNameList(nameList);

        salesTop10ReportVO.setNumberList(numberList);

        return salesTop10ReportVO;
    }

    /**用户统计*/
    @Override
    @Transactional

    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        if(begin == null || end == null){throw new DeletionNotAllowedException(MessageConstant.UNKNOWN_ERROR);}

        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.ofSecondOfDay(00 - 00 - 00));
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.ofSecondOfDay(00 - 00 - 00));
//        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);


        endTime = endTime.plusDays(1);

        //日期，以逗号分隔，例如：2022-10-01,2022-10-02,2022-10-03
        String dateList = "";

        //用户总量，以逗号分隔，例如：200,210,220
        String totalUserList = "";

        //新增用户，以逗号分隔，例如：20,21,10
        String newUserList = "";

        while (!beginTime.isEqual(endTime)){

            //当天的总用户数量
            Integer allCount = reportMapper.queryAllCount(beginTime.plusDays(1));//beginTime.plusDays(1)这里可用end来处理
            totalUserList = (begin.isEqual(end))?totalUserList + allCount : totalUserList + allCount + ",";

            //当天的新用户数量
            Integer newCount = allCount - reportMapper.queryNewCount(beginTime);
            newUserList = (begin.isEqual(end))?newUserList + newCount : newUserList + newCount + ",";

            dateList = (begin.isEqual(end))?dateList + beginTime : dateList + beginTime + ",";

            beginTime = beginTime.plusDays(1);

        }

        UserReportVO userReportVO = new UserReportVO();

        userReportVO.setDateList(dateList);
        userReportVO.setTotalUserList(totalUserList);
        userReportVO.setNewUserList(newUserList);
        return userReportVO;
    }

    /**订单统计接口*/
    @Override
    @Transactional

    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end)   {
        //判空
        if(begin == null || end == null){throw new DeletionNotAllowedException(MessageConstant.UNKNOWN_ERROR);}

        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.ofSecondOfDay(00 - 00 - 00));
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.ofSecondOfDay(00 - 00 - 00));

        //日期，以逗号分隔，例如：2022-10-01,2022-10-02,2022-10-03
        String dateList = "";

        //每日订单数，以逗号分隔，例如：260,210,215
        String orderCountList = "";

        //每日有效订单数，以逗号分隔，例如：20,21,10
        String validOrderCountList = "";

        //订单总数
        Integer totalOrderCount = 0;

        //有效订单数
        Integer validOrderCount = 0;

        //订单完成率
        Double orderCompletionRate;

        //获取天数
        while (!beginTime.isEqual(endTime)){
            //查询每日订单总数
            Integer orders = reportMapper.queryAllOrders(beginTime.toLocalDate(),beginTime.plusDays(1).toLocalDate());
            orderCountList = (beginTime.isEqual(endTime))?orderCountList + orders : orderCountList + orders + ",";

            //查询每日有效订单数
            Integer validOrdersByDay = reportMapper.queryValidOrdersByDay(beginTime,beginTime.plusDays(1),Orders.COMPLETED);
            validOrderCountList = (beginTime.isEqual(endTime))?validOrderCountList + validOrdersByDay : validOrderCountList + validOrdersByDay + ",";

            dateList = (begin.isEqual(end))?dateList + beginTime : dateList + beginTime + ",";
            beginTime = beginTime.plusDays(1);
        }

        //查询订单总数
        totalOrderCount = reportMapper.queryAllOrders(begin,end);

        //查询有效订单数
        validOrderCount = reportMapper.queryValidOrders(begin,end,Orders.COMPLETED);

        //计算订单完成率
        BigDecimal validOrderCountB = new BigDecimal(validOrderCount);
        BigDecimal totalOrderCountB = new BigDecimal(totalOrderCount);

        orderCompletionRate = validOrderCountB.divide(totalOrderCountB,4,BigDecimal.ROUND_HALF_UP).doubleValue();

        OrderReportVO orderReportVO =
                new OrderReportVO(dateList,
                        orderCountList,
                        validOrderCountList,
                        totalOrderCount,
                        validOrderCount,
                        orderCompletionRate);


        return orderReportVO;
    }

    /**导出文件*/
    @Override
    @Transactional
    public void exportExcel(HttpServletResponse response) throws IOException {
        //获取文件输入流
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        //查询近30天数据
        LocalDate date = LocalDate.now().minusDays(30);

        LocalDate now = LocalDate.now().minusDays(1);

        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(date,LocalTime.MIN),LocalDateTime.of(now,LocalTime.MAX));

        //获取营业额
        Double amount = reportMapper.QueryAmountByMonth(date,now,Orders.COMPLETED);//总营业额
        List<DataOrder> amounts = reportMapper.QueryAmount(Orders.COMPLETED,LocalDateTime.of(date,LocalTime.MIN),LocalDateTime.of(now,LocalTime.MAX));
        //新增用户数
        List<DataOrder> newMembers = reportMapper.queryNewCountByDay(date,now);//每日新增
        Integer newUsers = businessData.getNewUsers();//新增总数
        //有效订单
        Integer validOrder = reportMapper.queryValidOrders(date, now, Orders.COMPLETED);//有效订单的总数
        List<DataOrder> validOrders = reportMapper.queryValidAllOrderByDay(date, now, Orders.COMPLETED);//每日有效订单总数
        //订单完成率
        List<DataOrder> queryAllOrders = reportMapper.queryAllOrdersByDay(LocalDateTime.of(date,LocalTime.MIN),LocalDateTime.of(now,LocalTime.MAX));//每日订单总数
        BigDecimal bvalidOrder = new BigDecimal(validOrder);
        BigDecimal ballOrder= new BigDecimal(reportMapper.queryAllOrders(date, now));
        Double orderCompletionRate = bvalidOrder.divide(ballOrder,4,BigDecimal.ROUND_HALF_DOWN).doubleValue();//总订单完成率
        //平均客单价
        Double unitPrice = businessData.getUnitPrice();

        //创建对应文档的对象
        XSSFWorkbook sheets = new XSSFWorkbook(inputStream);
//获取页
        XSSFSheet sheet1 = sheets.getSheet("Sheet1");
//获取行
        XSSFRow row1 = sheet1.getRow(1);
        row1.getCell(1).setCellValue("日期:"+date+"至"+now);

        row1 = sheet1.getRow(3);

        //概览数据的设置
        //设置营业额
        row1.getCell(2).setCellValue(amount);
        //设置订单完成率
        row1.getCell(4).setCellValue(orderCompletionRate);
        //设置新增用户
        row1.getCell(6).setCellValue(newUsers);

        row1 = sheet1.getRow(4);
        //设置有效订单
        row1.getCell(2).setCellValue(validOrder);
        //设置平均客价
        row1.getCell(4).setCellValue(unitPrice);

        //明细数据的设置
        now = now.plusDays(1);
        int rownum = 7;
        while (!date.isEqual(now)){
            row1 = sheet1.getRow(rownum);
            //设置日期
            row1.getCell(1).setCellValue(String.valueOf(date));
            //设置营业额
            for (int i = 0; i < amounts.size(); i++) {
                if(amounts.get(i).getOrderTime().isEqual(date)){
                    row1.getCell(2).setCellValue(amounts.get(i).getAmount());
                    break;
                }
                row1.getCell(2).setCellValue(0.0);
            }

            //设置有效订单数
            for (int i = 0; i < validOrders.size(); i++) {

                Integer orderNum = validOrders.get(i).getOrderNum();
                if(validOrders.get(i).getOrderTime().isEqual(date)){
                    row1.getCell(3).setCellValue(orderNum);
                    break;
                }
                row1.getCell(3).setCellValue(0);

            }

            //订单完成率
            for (int i = 0; i < validOrders.size(); i++){
                if(validOrders.get(i).getOrderTime().isEqual(queryAllOrders.get(i).getOrderTime())
                    && date.isEqual(validOrders.get(i).getOrderTime())){
                    BigDecimal validorder = new BigDecimal(validOrders.get(i).getOrderNum());
                    BigDecimal allorder = new BigDecimal(queryAllOrders.get(i).getOrderTotal());
                    double orderCompletionRate1 = validorder.divide(allorder, 4, BigDecimal.ROUND_HALF_DOWN).doubleValue();
                    row1.getCell(4).setCellValue(orderCompletionRate1*100+"%");
                    break;
                }
                row1.getCell(4).setCellValue(0+"%");
            }

            //平均客价=>营业额/有效订单
            for (int i = 0; i < amounts.size(); i++) {
                if(amounts.get(i).getOrderTime().isEqual(date)){
                    BigDecimal validorder = new BigDecimal(validOrders.get(i).getOrderNum());
                    BigDecimal amountByDay = new BigDecimal(amounts.get(i).getAmount());
                    double value = amountByDay.divide(validorder, 4, BigDecimal.ROUND_HALF_DOWN).doubleValue();
                    row1.getCell(5).setCellValue(value);
                    break;
                }
                row1.getCell(5).setCellValue(0.0);
            }

            //新增用户
            for (int i = 0; i < newMembers.size(); i++) {
                if(newMembers.get(i).getOrderTime().isEqual(date)){
                    row1.getCell(6).setCellValue(newMembers.get(i).getPeople());
                    break;
                }
                row1.getCell(6).setCellValue(0);
            }

            rownum++;
            date = date.plusDays(1);
        }
        ServletOutputStream outputStream = response.getOutputStream();
        sheets.write(outputStream);


        sheets.close();
        outputStream.close();
    }
}
